import React, { useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectVideoById, updateVideoProperties } from '@/store/videosSlice';
import { selectStickerById, updateStickerProperties } from '@/store/stickersSlice';
import { Form, Input, InputNumber, Switch, Select, Typography, Row, Col, Slider, Button, message } from 'antd';
import type { Video } from '@/store/videoTypes';
import type { Sticker } from '@/store/stickerTypes';
import type { RootState } from '@/store';
import { createGlobalStyle } from 'styled-components';

const { Title, Text } = Typography;
const { Option } = Select;

interface ConfigVideoFormProps {
    videoId: string;
}

// 辅助组件：用于创建标签-滑块-数值输入的组合行
const SliderInputRow: React.FC<{
    label: string;
    name: any;
    sliderProps: any;
    inputProps: any;
}> = ({ label, name, sliderProps, inputProps }) => (
    <Form.Item>
        <Row align="middle" gutter={16}>
            <Col span={6}>
                <Text style={{ color: '#FFFFFF' }}>{label}</Text>
            </Col>
            <Col span={12}>
                <Form.Item name={name} noStyle>
                    <Slider {...sliderProps} />
                </Form.Item>
            </Col>
            <Col span={6}>
                <Form.Item name={name} noStyle>
                    <InputNumber style={{ width: '90%' }} {...inputProps} />
                </Form.Item>
            </Col>
        </Row>
    </Form.Item>
);

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* 自定义滚动条样式 */
    .config-video-form-scroll::-webkit-scrollbar {
        width: 3px;
        background: transparent;
    }
    .config-video-form-scroll::-webkit-scrollbar-thumb {
        background: #715BB8;
        border-radius: 4px;
    }
    /* Ant Design 表单标签颜色 */
    .ant-form-item-label > label {
        color: #FFFFFF !important;
    }
    /* 输入框 (Input, InputNumber), 选择框 (Select) */
    .ant-input,
    .ant-input-number,
    .ant-select-selector {
        background-color: #3C3C3C !important;
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus,
    .ant-input-number:hover, .ant-input-number:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important;
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap {
        background-color: #3C3C3C !important;
    }
    .ant-input-number-handler {
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-select-dropdown {
        background-color: #3C3C3C !important;
    }
    .ant-select-item-option {
        color: #FFFFFF !important;
    }
    .ant-select-item-option-selected {
        background-color: #555555 !important;
    }
    .ant-select-arrow {
        color: #FFFFFF !important;
    }
    /* 开关 (Switch) */
    .ant-switch {
        background-color: #555555 !important;
    }
    .ant-switch-checked {
        background-color: #715BB8 !important;
    }
    /* 滑块 (Slider) */
    .ant-slider-rail {
        background-color: #555555 !important;
    }
    .ant-slider-track {
        background-color: #FFFFFF !important;
    }
    .ant-slider-handle {
        border: solid 2px #FFFFFF !important;
        background-color: #3C3C3C !important;
    }
    .ant-slider-handle:focus {
        box-shadow: 0 0 0 5px rgba(255, 255, 255, 0.12) !important;
    }
`;

const ConfigVideoForm: React.FC<ConfigVideoFormProps> = ({ videoId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    const isSticker = videoId?.includes('sticker') || false;

    // 根据类型获取对应的素材数据
    const media = useSelector((state: RootState) => {
        if (!videoId) return null;
        return isSticker ? selectStickerById(state, videoId) : selectVideoById(state, videoId);
    });

    // 在组件加载或 media 变化时设置表单值
    useEffect(() => {
        if (media) {
            form.setFieldsValue({
                videoName: media.name,
                target_timerange_start: media.target_timerange[0],
                target_timerange_duration: media.target_timerange[1],
                source_timerange_start: media.source_timerange[0],
                source_timerange_duration: media.source_timerange[1],
                speed: 'speed' in media ? media.speed : 1, // 贴纸可能没有speed属性
                volume: 'volume' in media ? media.volume : 1, // 贴纸可能没有volume属性
                clip_settings: media.clip_settings,
            });
        }
    }, [media, form]);

    // 处理表单值变化，更新Redux
    const handleValuesChange = useCallback(
        (changedValues: any, allValues: any) => {
            if (!videoId || !media) return;

            // 根据类型构建要更新的对象
            const updates: Partial<Video | Sticker> = {};

            // 检查每个可能变化的字段
            if ('videoName' in changedValues) updates.name = allValues.videoName;
            if ('target_timerange_start' in changedValues || 'target_timerange_duration' in changedValues) {
                // 对于贴纸，验证目标持续时间必须小于5秒
                if (isSticker && allValues.target_timerange_duration >= 5) {
                    message.error('贴纸持续时间必须小于5秒');
                    return; // 不更新数据
                }
                updates.target_timerange = [allValues.target_timerange_start, allValues.target_timerange_duration];
            }
            if (!isSticker && ('source_timerange_start' in changedValues || 'source_timerange_duration' in changedValues)) {
                updates.source_timerange = [allValues.source_timerange_start, allValues.source_timerange_duration];
            }
            // 只有视频有speed和volume属性
            if (!isSticker) {
                if ('speed' in changedValues) updates.speed = allValues.speed;
                if ('volume' in changedValues) updates.volume = allValues.volume;
            }

            // 合并 clip_settings
            if ('clip_settings' in changedValues) {
                updates.clip_settings = {
                    ...media.clip_settings,
                    ...allValues.clip_settings,
                };
            }

            if (Object.keys(updates).length > 0) {
                if (isSticker) {
                    // 更新贴纸数据
                    dispatch(
                        updateStickerProperties({
                            id: videoId,
                            updates: { ...media, ...updates },
                        })
                    );
                } else {
                    // 更新视频数据
                    dispatch(
                        updateVideoProperties({
                            id: videoId,
                            updates: { ...media, ...updates },
                        })
                    );
                }
            }
        },
        [videoId, media, isSticker, dispatch]
    );

    if (!media) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                {isSticker ? '未选择贴纸片段' : '未选择视频片段'}
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            {/* **改动1: 主容器样式与之前表单对齐** */}
            <div
                className="config-video-form-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前选择
                </Title>
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '16px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>
                        {isSticker ? (
                            <>
                                <i className="icon-sticker">🎨</i> {media.name || '未命名贴纸'}
                            </>
                        ) : (
                            <>
                                <i className="icon-video">▶️</i> {media.name || '未命名视频'}
                            </>
                        )}
                    </Text>
                </div>

                <Form form={form} layout="vertical" onValuesChange={handleValuesChange}>
                    <Title level={5} style={{ color: '#FFFFFF', marginTop: 0 }}>
                        基础信息
                    </Title>
                    <Form.Item name="videoName" label="视频名称" rules={[{ required: true, message: '请输入视频名称' }]}>
                        <Input placeholder="请输入视频名称" style={{ width: '98%' }} />
                    </Form.Item>

                    <Title level={5} style={{ color: '#FFFFFF', marginTop: 24 }}>
                        时间范围
                    </Title>
                    {/* **改动2: 优化布局，将相关字段并排显示** */}
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="目标开始 (秒)" name="target_timerange_start">
                                <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="目标持续 (秒)" name="target_timerange_duration">
                                <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                    </Row>
                    {!isSticker && (
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item label="源开始 (秒)" name="source_timerange_start">
                                    <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="源持续 (秒)" name="source_timerange_duration">
                                    <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                                </Form.Item>
                            </Col>
                        </Row>
                    )}

                    {!isSticker && (
                        <>
                            <Title level={5} style={{ color: '#FFFFFF', marginTop: 24 }}>
                                播放设置
                            </Title>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Form.Item label="速度" name="speed">
                                        <Select style={{ width: '198%' }}>
                                            <Option value={1}>1倍速</Option>
                                            <Option value={2}>2倍速</Option>
                                            <Option value={3}>3倍速</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                            </Row>

                            {/* 使用SliderInputRow组件实现推拉线样式 */}
                            <SliderInputRow label="音量" name="volume" sliderProps={{ min: 0, max: 1, step: 0.1 }} inputProps={{ min: 0, max: 1, step: 0.1 }} />
                        </>
                    )}

                    <Title level={5} style={{ color: '#FFFFFF', marginTop: 24 }}>
                        剪辑设置
                    </Title>
                    <SliderInputRow label="透明度" name={['clip_settings', 'alpha']} sliderProps={{ min: 0, max: 1, step: 0.01 }} inputProps={{ min: 0, max: 1, step: 0.01 }} />

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="水平翻转" name={['clip_settings', 'flip_horizontal']} valuePropName="checked">
                                <Switch />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="垂直翻转" name={['clip_settings', 'flip_vertical']} valuePropName="checked">
                                <Switch />
                            </Form.Item>
                        </Col>
                    </Row>

                    <SliderInputRow
                        label="旋转角度"
                        name={['clip_settings', 'rotation']}
                        sliderProps={{ min: 0, max: 360, step: 1 }}
                        inputProps={{
                            min: 0,
                            max: 360,
                            step: 1,
                            addonAfter: '°',
                        }}
                    />

                    <SliderInputRow label="X轴缩放" name={['clip_settings', 'scale_x']} sliderProps={{ min: 0.1, max: 1, step: 0.1 }} inputProps={{ min: 0.1, max: 1, step: 0.1 }} />

                    <SliderInputRow label="Y轴缩放" name={['clip_settings', 'scale_y']} sliderProps={{ min: 0.1, max: 1, step: 0.1 }} inputProps={{ min: 0.1, max: 1, step: 0.1 }} />

                    <SliderInputRow label="X轴平移" name={['clip_settings', 'transform_x']} sliderProps={{ min: -1, max: 1, step: 0.1 }} inputProps={{ min: -1, max: 1, step: 0.1 }} />

                    <SliderInputRow label="Y轴平移" name={['clip_settings', 'transform_y']} sliderProps={{ min: -1, max: 1, step: 0.1 }} inputProps={{ min: -1, max: 1, step: 0.1 }} />
                </Form>
            </div>
        </>
    );
};
export default ConfigVideoForm;
